package cn.com.twoke.application.game.mario.core.engine;

import cn.com.twoke.application.game.mario.core.ecs.component.InputState;
import cn.com.twoke.application.game.mario.core.ecs.entity.Entity;
import cn.com.twoke.application.game.mario.core.ecs.system.RenderGameSystem;
import lombok.Getter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

public class GamePanel extends JPanel {


    private final List<Entity> entities;
    @Getter
    private final InputState inputState;
    private final RenderGameSystem renderSystem;

    public GamePanel(List<Entity> entities, InputState inputState, RenderGameSystem renderSystem) {
        this.entities = entities;
        this.inputState = inputState;
        this.renderSystem = renderSystem;
        this.renderSystem.setContainer(this);
        setBackground(Color.BLACK);
        setFocusable(true);
        requestFocusInWindow();

        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                inputState.keyPressed(e.getKeyCode());
            }

            @Override
            public void keyReleased(KeyEvent e) {
                inputState.keyReleased(e.getKeyCode());
            }
        });

        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                inputState.mouseMoved(e.getX(), e.getY());
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                inputState.mouseMoved(e.getX(), e.getY());
            }
        });

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                inputState.mouseMoved(e.getX(), e.getY());
            }
        });
    }

    /**
     * 绘制游戏区域
     *
     * @param gameAreaGraphics 游戏区域绘制画笔
     */
    @Override
    protected void paintComponent(Graphics gameAreaGraphics) {
        super.paintComponent(gameAreaGraphics);
        this.renderSystem.render(entities, (Graphics2D) gameAreaGraphics);
    }

}